<template>
	<div id="addQuestion">
		<div class="title" v-if="!edit">创建题目</div>
		<div v-else class="title">编辑题目</div>
		<el-form ref="formRef" :model="formData" :rules="rules" hide-required-asterisk="true" label-width="auto">
			<el-form-item prop="title" label-width="150px" label-position="right">
				<template v-slot:label>
					<span style="color: black; font-weight: bold">题目标题</span>
				</template>
				<el-input v-model="formData.title" style="width: 300px" placeholder="请输入题目的标题"></el-input>
			</el-form-item>
			<el-form-item prop="tags" label-width="150px" label-position="right">
				<template v-slot:label>
					<span style="color: black; font-weight: bold">标签</span>
				</template>
				<div class="flex gap-2">
					<el-tag
						v-model="formData.tags"
						v-for="tag in formData.tags"
						:key="tag"
						effect="dark"
						size="large"
						:type="'primary'"
						closable
						:disable-transitions="false"
						@close="handleClose(tag)"
					>
						{{ tag }}
					</el-tag>
					<el-input
						v-if="inputVisible"
						ref="InputRef"
						style="width: 100px"
						v-model="inputValue"
						@keyup.enter="handleInputConfirm"
						@blur="handleInputConfirm"
					/>
					<el-button type="success" plain v-else @click="showInput"> + 新的标签 </el-button>
				</div>
			</el-form-item>
			<el-form-item label-width="150px" label-position="right">
				<template v-slot:label>
					<span style="color: black; font-weight: bold">判题配置</span>
				</template>
				<div style="margin-right: 10px">
					时间限制
					<el-input-number v-model="formData.judgeConfig.timeLimit" :min="1" :max="10000" />
				</div>
				<div style="margin-right: 10px">
					内存限制
					<el-input-number v-model="formData.judgeConfig.memoryLimit" :min="1" :max="10000" />
				</div>
				<div>
					堆栈限制
					<el-input-number v-model="formData.judgeConfig.stackLimit" :min="1" :max="10000" />
				</div>
			</el-form-item>
			<el-form-item prop="content" label-width="150px" label-position="right">
				<template v-slot:label>
					<span style="color: black; font-weight: bold">题目内容</span>
				</template>
				<MdEditor style="width: 80%" ref="mdEditor" :mdValue="formData.content" :onMdChange="onMdChange" />
			</el-form-item>
			<el-form-item prop="answer" label-width="150px" label-position="right">
				<template v-slot:label>
					<span style="color: black; font-weight: bold">题目答案</span>
				</template>
				<CodeEditor :codeValue="formData.answer" :onCodeChange="onCodeChange" ref="codeMirror" />
			</el-form-item>
			<template v-for="(domain, index) in formData.judgeCase" :key="domain.key">
				<div style="display: flex; justify-content: left">
					<el-form-item label-width="250px" :label="'输入用例 ' + index">
						<el-input style="width: 150px" v-model="domain.input" />
					</el-form-item>
					<el-form-item label-width="150px" :label="'输出用例 ' + index">
						<el-input style="width: 150px" v-model="domain.output"
					/></el-form-item>
					<el-button style="margin-left: 20px" class="mt-2" type="danger" @click.prevent="removeDomain(domain)">
						删除用例
					</el-button>
				</div>
			</template>

			<el-form-item label-width="150px">
				<el-button @click="addDomain" type="success" plain> + 新的用例</el-button>
				<el-button class="button" type="primary" @click="submit" :loading="loading">提交</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script setup>
import { ref, nextTick, reactive, onMounted, watch } from "vue";
import MdEditor from "@/components/MdEditor.vue";
import CodeEditor from "@/components/CodeEditor.vue";
import { addQuestion, getQuestionDetail, updateQuestion } from "@/api/question";
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const edit = ref(false);

// 定义响应式状态
const inputValue = ref("");
const inputVisible = ref(false);
const InputRef = ref();
const formRef = ref();
const loading = ref(false);
const router = useRouter();

const formData = reactive({
	answer: "",
	content: "",
	judgeCase: [
		{
			input: "",
			output: ""
		}
	],
	judgeConfig: {
		memoryLimit: 1000,
		stackLimit: 1000,
		timeLimit: 1000
	},
	tags: [],
	title: ""
});
const rules = reactive({
	title: [{ required: true, message: "题目标题不能为空", trigger: "blur" }]
});

// 方法定义
const handleClose = tag => {
	formData.tags = formData.tags.filter(t => t !== tag);
};
watch(
	() => route.path,
	val => {
		if (val === "/update/question") {
			edit.value = true;
		} else if (val === "/add/question") {
			edit.value = false;
			formData.title = "";
			formData.tags = [];
			formData.content = "";
			formData.answer = "";
			formData.judgeCase = [
				{
					input: "",
					output: ""
				}
			];
			formData.judgeConfig = {
				memoryLimit: 1000,
				stackLimit: 1000,
				timeLimit: 1000
			};
		}
	},
	{
		deep: true,
		immediate: true
	}
);

const showInput = () => {
	inputVisible.value = true;
	nextTick(() => {
		InputRef.value?.focus?.(); // 假设Element Plus的输入框有focus方法
	});
};

const handleInputConfirm = () => {
	if (inputValue.value) {
		formData.tags.push(inputValue.value);
	}
	inputVisible.value = false;
	inputValue.value = "";
};

const onMdChange = v => {
	formData.content = v;
};

const onCodeChange = v => {
	formData.answer = v;
};

const submit = () => {
	formRef.value.validate(valid => {
		if (valid) {
			loading.value = true;
			const params = {
				answer: formData.answer,
				content: formData.content,
				judgeCase: formData.judgeCase,
				judgeConfig: formData.judgeConfig,
				tags: formData.tags,
				title: formData.title
			};
			if (edit.value) {
				updateQuestion({ ...params, id: route.query.id }).then(res => {
					if (res.code !== 0) {
						ElMessage.error(res.message);
						loading.value = false;
						return;
					}
					ElMessage.success("更新成功");
					formRef.value.resetFields();
					loading.value = false;
					router.push("/questions");
				});
			} else {
				addQuestion(params).then(res => {
					if (res.code !== 0) {
						ElMessage.error(res.message);
						loading.value = false;
						return;
					}
					ElMessage.success("添加成功");
					formRef.value.resetFields();
					loading.value = false;
					router.push("/questions");
				});
			}
		} else {
			return false;
		}
	});
};

const removeDomain = item => {
	const index = formData.judgeCase.indexOf(item);
	if (index !== -1) {
		formData.judgeCase.splice(index, 1);
	}
};

const addDomain = () => {
	formData.judgeCase.push({});
};

const getDetail = async () => {
	const id = route.query.id;
	if (!id) {
		return;
	}
	const res = await getQuestionDetail(id);
	if (res.code === 0) {
		formData.answer = res.data.answer;
		formData.content = res.data.content;
		formData.judgeCase = JSON.parse(res.data.judgeCase);
		formData.judgeConfig = JSON.parse(res.data.judgeConfig);
		formData.tags = JSON.parse(res.data.tags);
		formData.title = res.data.title;
	} else {
		ElMessage.error(`获取题目详情失败：${res.message || "未知错误"}`);
	}
};

onMounted(() => {
	getDetail();
});
</script>

<style scoped lang="scss">
#addQuestion {
	display: flex;
	flex-direction: column;
	// align-items: center;
	.title {
		font-size: 24px;
		font-weight: bold;
		text-align: left;
		margin-bottom: 15px;
	}
	.el-form {
		.gap-2 {
			display: flex;
			.el-tag {
				margin-right: 10px;
			}
		}
	}
}
</style>
